package com.zg.message.task;

import com.zg.common.core.dao.message.entity.MsgInfo;
import com.zg.message.channel.ChannelRouter;
import com.zg.message.service.MsgInfoService;
import com.zg.message.sys.MsgTypeEnum;
import com.zg.message.sys.SendStateEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/7/9 16:09
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmailMsgSendTask {

    private final ChannelRouter channelRouter;

    private final MsgInfoService msgInfoService;

    @Async("mainExecutor")
    public void processNewMessages() throws InterruptedException {
        while (true) {
            try {
                List<MsgInfo> messages = msgInfoService.listBySendState(SendStateEnum.INIT.getValue(), MsgTypeEnum.SMS.getValue());
                if (messages.isEmpty()) {
                    Thread.sleep(5000); // 无消息时等待1秒
                    continue;
                }
                messages.stream().forEach(t->{
                    channelRouter.routeAndSend(t);
                });
            } catch (Exception e) {
                log.error("主处理线程异常", e);
                Thread.sleep(1000);
            }
        }
    }

}
